package servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/ColumnOptionsServlet")
public class ColumnOptionsServlet extends HttpServlet {
    private static final String URL = "jdbc:mysql://localhost:3306/people";
    private static final String USER = "root";
    private static final String PASSWORD = "nmnm1239";

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        JSONArray columnOptions = new JSONArray(); // 存储列名的 JSON 数组

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }

        try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet rs = metaData.getColumns(null, null, "user", null); // 这里的 "user" 是数据库表的名称，根据你的实际表名进行修改
            while (rs.next()) {
                String columnName = rs.getString("COLUMN_NAME");
                columnOptions.add(columnName);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return;
        }

        JSONObject result = new JSONObject();
        result.put("data", columnOptions);

        out.println(result.toJSONString());
        out.close();
    }
}
